﻿/* 
 * 
 * Copyright 2013 Bendsoft. All rights reserved.
 * http://www.bendsoft.com
 * 
 * This code is distributed under the New BSD License (BSD).
 * 
 * @package     Camelot SharePoint Integration Plugins Library
 * @codeplex    http://camelottoolkit.codeplex.com
 * @license     New BSD License (BSD)
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Camelot.SharePointIntegration.IntegrationService;
using Camelot.SharePointIntegration.IntegrationService.Entities;
using Camelot.SharePointIntegration.Client;

namespace Camelot.SharePointIntegration.Plugins
{
    public class CamelotXmlToFtp : ListDataPlugin
    {
        protected override ServicePluginResult ProcessData(Task task, ListData data, List<Parameter> parameters)
        {
            string hostname = (from p in parameters where p.Name.ToLower() == "hostname" select p.Value).FirstOrDefault();
            string username = (from p in parameters where p.Name.ToLower() == "username" select p.Value).FirstOrDefault();
            string password = (from p in parameters where p.Name.ToLower() == "password" select p.Value).FirstOrDefault();
            string port = (from p in parameters where p.Name.ToLower() == "port" select p.Value).FirstOrDefault();
            string folder = (from p in parameters where p.Name.ToLower() == "folder" select p.Value).FirstOrDefault();

            if (String.IsNullOrEmpty(hostname))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter null or empty: hostname" };

            if (String.IsNullOrEmpty(username))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter null or empty: username" };

            if (String.IsNullOrEmpty(password))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter null or empty: password" };

            if (String.IsNullOrEmpty(port))
                port = "21";

            var uri = "ftp://" + 
                hostname + ":" + port + 
                (!String.IsNullOrEmpty(folder) ? "/" + folder.Trim('/') + "/" : "/") + 
                DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";

            var xml = CamelotXml.CreateXml(data);
            var xmlBinary = System.Text.Encoding.UTF8.GetBytes(xml);
            var statusDescription = Utilities.FtpUploadFile(uri, xmlBinary, username, password);

            return new IntegrationService.ServicePluginResult() { Success = true, Message = statusDescription };
        }
    }
}
